import numpy as np

class Config:
    """幅度相位转换配置"""
    EFFECTIVE_LENGTH = 0.855  # 有效长度
    POWER_SCALE = 1000       # 功率缩放因子
    VOLTAGE_SCALE = 1000     # 电压缩放因子

def validate_input_data(raw_powers):
    """验证输入数据的完整性
    
    Args:
        raw_powers (dict): 原始数据字典
        
    Raises:
        KeyError: 当缺少必要的键时
    """
    required_keys = [
        "mag_cav", "phase_cav",
        "mag_for", "phase_for",
        "mag_refl", "phase_refl"
    ]
    
    missing_keys = [key for key in required_keys if key not in raw_powers]
    if missing_keys:
        raise KeyError(f"缺少必要的键: {', '.join(missing_keys)}")

def calibrate_magnitudes(mag_cav, mag_for, mag_refl, RQ, Qext, beta):
    """校准幅度值
    
    Args:
        mag_cav, mag_for, mag_refl (ndarray): 原始幅度数据
        RQ (float): 电阻品质因数乘积
        Qext (float): 外部品质因数
        beta (float): 耦合系数
        
    Returns:
        tuple: 校准后的幅度值
    """
    # 腔体幅度校准
    cav_cal = mag_cav
    
    # 前向和反射功率校准
    power_factor = RQ * Qext * (1 + beta) / beta
    scale = Config.POWER_SCALE
    
    for_cal = np.sqrt(np.abs(mag_for * scale * power_factor)) / Config.VOLTAGE_SCALE
    refl_cal = np.sqrt(np.abs(mag_refl * scale * power_factor)) / Config.VOLTAGE_SCALE
    
    return cav_cal, for_cal, refl_cal

def convert_to_iq(magnitude, phase):
    """将幅度和相位转换为IQ分量
    
    Args:
        magnitude (ndarray): 幅度数据
        phase (ndarray): 相位数据（度）
        
    Returns:
        tuple: I和Q分量
    """
    phase_rad = np.deg2rad(phase)
    return (
        magnitude * np.cos(phase_rad),
        magnitude * np.sin(phase_rad)
    )

def mag_phase_to_IQ(raw_powers, RQ, Qext, beta):
    """将幅度和相位数据转换为IQ电压
    
    Args:
        raw_powers (dict): 包含幅度和相位数据的字典
        RQ (float): 电阻品质因数乘积
        Qext (float): 外部品质因数
        beta (float): 耦合系数
    
    Returns:
        dict: 包含IQ电压的字典
    """
    # 验证输入数据
    validate_input_data(raw_powers)
    
    # 提取原始数据
    mag_cav = raw_powers["mag_cav"]
    phase_cav = raw_powers["phase_cav"]
    mag_for = raw_powers["mag_for"]
    phase_for = raw_powers["phase_for"]
    mag_refl = raw_powers["mag_refl"]
    phase_refl = raw_powers["phase_refl"]
    
    # 校准幅度
    mag_cav_cal, mag_for_cal, mag_refl_cal = calibrate_magnitudes(
        mag_cav, mag_for, mag_refl, RQ, Qext, beta
    )
    
    # 转换为IQ分量
    Vcav_I, Vcav_Q = convert_to_iq(mag_cav_cal, phase_cav)
    Vfor_I, Vfor_Q = convert_to_iq(mag_for_cal, phase_for)
    Vrefl_I, Vrefl_Q = convert_to_iq(mag_refl_cal, phase_refl)
    
    # 返回结果
    return {
        "Vcav_I": Vcav_I, "Vcav_Q": Vcav_Q,
        "Vfor_I": Vfor_I, "Vfor_Q": Vfor_Q,
        "Vrefl_I": Vrefl_I, "Vrefl_Q": Vrefl_Q
    }